package org.jeecg.modules.yw.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.service.*;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.utils.UserUtil;
import org.jeecg.modules.yw.vo.MeasureAppointV;
import org.jeecg.modules.yw.vo.OrderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "统计管理")
@RequestMapping("/orderView")
public class OrderViewController  extends JeecgController<OrderView,OrderViewService>{
    @Autowired
    private OrderViewService orderViewService;
    @Autowired
    private GuaranteeService guaranteeService;
    @Resource
    private OrderService orderService;
    @Resource
    private PageInfoService pagerService;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private MeasureAppointService measureAppointService;

    @ApiOperation(value = "结算单")
    @GetMapping("/bill")
    public Result bill(Page<OrderView> page,
                       @RequestParam(value = "name", required = false)String name,
                       @RequestParam(value = "start", required = false) String start,
                       @RequestParam(value = "end", required = false) String end,
                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize ) {
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        QueryWrapper<OrderView> queryWrapper = new QueryWrapper<>();
        if(name != null) {
            queryWrapper.like("name", name);
        }
        if(start != null) {
            queryWrapper.ge("yytime", start);
        }
        if(end != null) {
            queryWrapper.le("yytime", end);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null))";
                queryWrapper.apply("createUserId in"+sql+"");
            }else{
                IPage<EnterPrise> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
        }
        queryWrapper.ge("orderStatus",11);
        queryWrapper.orderByDesc("createtime");
        IPage<OrderView> result = orderViewService.page(page,queryWrapper);
        result.getRecords().forEach(item->{
            Double mj=item.getMj();
            Double je=item.getJe();
            OrderVo order = orderService.getByVoId(item.getId());
            String problem="没问题";
            if(order!=null){
                BeanUtils.copyProperties(order,item);
                Integer cshs=item.getCshs();
                if (cshs!=null && cshs==0){
                    problem="有问题";
                }
                Integer dkfc=item.getDkfc();
                if (dkfc!=null && dkfc==2){
                    problem="有问题";
                }
            }
            item.setProblem(problem);
            item.setOrderno(order.getOrderNo());
            item.setMj(mj);
            item.setJe(je);
            QueryWrapper<PaperInfo> qw = new QueryWrapper<>();
            qw.eq("orderId", item.getId());
            List<PaperInfo> list = pagerService.list(qw);
            item.setPaperInfoList(list);
        });
        return Result.ok (result);
    }
    @ApiOperation(value = "中控---订单管理")
    @GetMapping("/getPage")
    public org.jeecg.common.api.vo.Result getPage(@RequestParam(name = "start", required = false) String start,
                                                  @RequestParam(name = "end", required = false) String end,
                                                  @RequestParam(name = "orderStatus", required = false) String orderStatus,
                                                  @RequestParam(value = "orderno", required = false) String orderno,
                                                  @RequestParam(name = "cardid", required = false) String cardid,
                                                  @RequestParam(name = "problem",  required = false) String problem,
                                                  @RequestParam(name = "name",  required = false) String name,
                                                  @RequestParam(name = "ownerPhone",  required = false) String ownerPhone,
                                                  @RequestParam(name = "pageNo") Integer pageNo,
                                                  @RequestParam(name = "pageSize") Integer pageSize) {
        IPage<OrderVo> page = new Page<>(pageNo, pageSize);
        Date startDate=null;
        Date endDate=null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(start)) {
            startDate= DateUtils.strToDate(start);
        }
        if (StringUtils.isNotBlank(end)) {
            endDate=DateUtils.strToDate(end);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        String[] areas=null;
        String[] enters=null;
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
                areas=area.split(",");
            }else{
                IPage<OrderVo> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
            if(!roleIds.contains(CommonUtils.NQZG)){
                String enter=sysUser.getCompanyId();
                if(StringUtils.isNotBlank(enter)){
                    enters=enter.split(",");
                }else{
                    IPage<OrderVo> result =new Page<>();
                    return org.jeecg.common.api.vo.Result.ok(result);
                }
            }
        }
        IPage<OrderVo> result = orderService.getPage(page, startDate, endDate, orderStatus, orderno, cardid, problem,areas,enters,name, ownerPhone);
        result.getRecords().forEach(item -> {
            Integer cshs=item.getCshs();
            String sproblem="没问题";
            if (cshs!=null && cshs==0){
                sproblem="有问题";
            }
            Integer dkfc=item.getDkfc();
            if (dkfc!=null && dkfc==2){
                sproblem="有问题";
            }
            item.setProblem(sproblem);
            Double mj=item.getMj();
            if (mj!=null && mj!=0){
                item.setMj(CommonUtils.scientificToNumber(mj.toString()));
            }
            Double je=item.getJe();
            if(je!=null&&je!=0) {
                item.setJe(CommonUtils.scientificToNumber(je.toString()));
            }
            QueryWrapper<PaperInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId", item.getId());
            List<PaperInfo> list = pagerService.list(queryWrapper);
            item.setPaperInfoList(list);
        });
        return org.jeecg.common.api.vo.Result.ok(result);
    }
    @ApiOperation(value = "中控---预约量尺分页")
    @GetMapping("/appointPage")
    public org.jeecg.common.api.vo.Result appointPage(@RequestParam(name = "start", required = false) String start,
                                                      @RequestParam(name = "end", required = false) String end,
                                                      @RequestParam(name = "pageNo") Integer pageNo,
                                                      @RequestParam(name = "pageSize") Integer pageSize) {
        IPage<MeasureAppointV> page = new Page<>(pageNo, pageSize);
        Date startDate=null;
        if (StringUtils.isNotBlank(start)) {
            startDate=DateUtils.strToDate(start);
        }
        Date endDate=null;
        if (StringUtils.isNotBlank(end)) {
            endDate=DateUtils.strToDate(end);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        String[] areas=null;
        String[] enters=null;
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
                areas=area.split(",");
            }else{
                IPage<MeasureAppointV> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
            if(!roleIds.contains(CommonUtils.NQZG)){
                String enter=sysUser.getCompanyId();
                if(StringUtils.isNotBlank(enter)){
                    enters=enter.split(",");
                }else{
                    IPage<MeasureAppointV> result =new Page<>();
                    return org.jeecg.common.api.vo.Result.ok(result);
                }
            }
        }
        IPage<MeasureAppointV> result = measureAppointService.appointPage(page, startDate, endDate,areas,enters);
        return org.jeecg.common.api.vo.Result.ok(result);
    }
    @ApiOperation(value = "结算单导出")
    @GetMapping("/exportbill")
    public ModelAndView exportbill(HttpServletRequest request,
                       @RequestParam(value = "name", required = false)String name,
                       @RequestParam(value = "start", required = false) String start,
                       @RequestParam(value = "end", required = false) String end,
                       @RequestParam(value = "ids", required = false) String ids) {
        QueryWrapper<OrderView> queryWrapper = new QueryWrapper<>();
        List<OrderView> list= null;
        String user= UserUtil.getUserName(request);
        if(ids != null) {
            String[] idss= ids.split(",");
            queryWrapper.in("id",idss);
            list = orderViewService.list(queryWrapper);
        }else{
            if(name != null) {
                queryWrapper.like("ownername", name);
            }
            if(start != null) {
                queryWrapper.ge("yytime", start);
            }
            if(end != null) {
                queryWrapper.le("yytime", end);
            }
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
            if (!roleIds.contains(CommonUtils.ADMIN)) {
                String area=sysUser.getArea();
                if(StringUtils.isNotBlank(area)){
                    String[] areas=area.split(",");
                    StringBuffer st=new StringBuffer();
                    for (int i = 0; i < areas.length; i++) {
                        st.append("\""+areas[i]+"\",");
                    }
                    st=st.deleteCharAt(st.length()-1);
                    String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                            "or (province_code in  ("+st.toString()+") and city_code is null))";
                    queryWrapper.apply("createUserId in"+sql+"");
                }else{
                    return super.exportXls(new ArrayList<>(), OrderView.class,user, "结算单");
                }
            }
            list = orderViewService.list(queryWrapper);
        }
        return super.exportXls(list, OrderView.class,user, "结算单");
    }
    @ApiOperation(value = "质保卡")
    @GetMapping("/guarantee")
    public Result guarantee(@RequestParam(name = "pageNo") Integer pageNo,
                       @RequestParam(name = "pageSize") Integer pageSize ) {
        Page<Guarantee> page= new Page<>();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String[] areas=null;
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
               areas=area.split(",");
            }
        }
        return Result.ok (guaranteeService.pageInfo(page,areas));
    }
}
